package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicModePaymentTestDO;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutDO;
import com.cssy.xxkj.logic.entity.LogicProductionStorageoutItemDO;
import com.cssy.xxkj.logic.entity.LogicReceptDO;
import com.cssy.xxkj.logic.entity.LogicReceptItemDO;
import com.cssy.xxkj.logic.entity.LogicSalesDO;
import com.cssy.xxkj.logic.service.ILogicProductionStorageOutService;
import com.cssy.xxkj.logic.service.ILogicReceptService;
import com.cssy.xxkj.logic.service.ILogicSalesService;
import com.cssy.xxkj.logic.service.ILogicUtilService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 收款
 * @author zeyong.gui
 *
 */
@Controller
@RequestMapping("/logic/recept")
public class ReceptController extends BaseController<LogicReceptDO> {
	
	private static final String MANAGER = "/xxkj/logic/recept/ReceptManager";
	private static final String EIDT = "/xxkj/logic/recept/ReceptOperation";
	
	@Resource(name = "logicReceptService")
	ILogicReceptService logicReceptService;
	
	@Resource(name = "logicSalesService")
	ILogicSalesService logicSalesService;
	
	@Resource(name = "logicProductionStorageOutService")
	ILogicProductionStorageOutService logicProductionStorageOutService;
	
	@Resource(name = "basicUtilService")
	IBasicUtilService basicUtilService;
	
	@Resource(name = "logicUtilService")
	ILogicUtilService logicUtilService;

	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		String zd009CustId = request.getParameter("zd009CustId");
		if(StringUtils.isNotBlank(zd009CustId)){
			scs.addCondition("zd009CustId", zd009CustId, SearchCondition.OP_EQUAL);
		}else{
			
		}
		String zdStatus = request.getParameter("zd003Status");
		if(StringUtils.isNotBlank(zdStatus)){
			if("".equals(zdStatus)){
				//scs.addCondition("zd009CustCode", custCode, SearchCondition.OP_EQUAL);
			}else{
				//scs.addCondition("zd009CustCode", custCode, SearchCondition.OP_EQUAL);
			}
		}
		SearchResult result = logicReceptService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			model.addAttribute("flag", "ADD");
			//查询生产出库单
			SearchConditions prodOutScs = new SearchConditions();
			prodOutScs.setRemovedProperty(null);
			List<LogicProductionStorageoutDO> prodOutList = logicUtilService.resultStagout(prodOutScs);
			model.addAttribute("prodOutList", prodOutList);
			//查询付款方式
			SearchConditions payScs = new SearchConditions();
			payScs.setRemovedProperty(null);
			List<BasicModePaymentTestDO> payList = basicUtilService.resultPayments(payScs);
			model.addAttribute("payList", payList);
		} else {
			LogicReceptDO recept = logicReceptService.findListById(id);
			model.addAttribute("recept", recept);
			
		}
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicReceptDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try{
			String itemdata = request.getParameter("dataitem");
			if(StringUtils.isBlank(itemdata)){
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			String flagMark = request.getParameter("flagMark");
			curAP.setZd003Status(flagMark);
			if(BillStatusUtil.RECEPT_BILL_STATUS_ONE.equals(flagMark)){
				logicReceptService.receptSave(curAP, request);
			}
			if(BillStatusUtil.RECEPT_BILL_STATUS_TWO.equals(flagMark)){
				logicReceptService.receptCommit(curAP, request);
			}
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
				String ids = request.getParameter("ids");
				String[] fields=ids.split(",");
				for(String field : fields){
					if(StringUtils.isBlank(field)){
						continue;
					}else{
						logicReceptService.deleteBizRemoved(field);
					}
				}
				bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			} catch (Exception e) {
				e.printStackTrace();
				bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
			}
			return bodyMap.modelMap;
	}

	/**
	 * ligerUI树的json
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		scs.setRemovedProperty(null);
		hander.getWheresNotLimit(scs);
		List<BasicCompanyTestDO> list =basicUtilService.resultCompany(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	/**
	 * 查询收款的item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/gridItems")
	public void gridItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String receptId = request.getParameter("receptId");
		if(StringUtils.isNotBlank(receptId)){ 
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("receptId", receptId);
			List<LogicReceptItemDO> repmList = logicReceptService.findItemListByMap(paramMap);
			OutJsonGrid out = new OutJsonGrid(repmList);
			out.printJSon(response);
		}
	}
	
	@RequestMapping("/prodSaleQuery")
	@ResponseBody
	public LogicReceptDO prodSaleQuery(HttpServletRequest request, Model model)
			throws Exception {
		LogicReceptDO recpMoney = new LogicReceptDO();
		BigDecimal recpSum = BigDecimal.ZERO;
		try{
			//销售订单号
			String saleCode = request.getParameter("saleCode");
			SearchConditions saleScs = new SearchConditions();
			saleScs.setRemovedProperty(null);
			saleScs.addCondition("zd001FormCode", saleCode, SearchCondition.OP_EQUAL);
			List<LogicSalesDO> saleList = logicUtilService.resultSales(saleScs);
			if(saleList==null||saleList.isEmpty()||saleList.size()==0){
				recpMoney.setZd010ExRateVal(null);
				recpMoney.setZd010ExRateCode("");
				recpMoney.setZd010ExRateName("");
			}else{
				/*recpMoney.setZd010ExRateVal(saleList.get(0));
				recpMoney.setZd010ExRateCode(saleList.get(0).getZd002CurrencyCode());
				recpMoney.setZd010ExRateName(saleList.get(0).getZd001CurrencyName());*/
			}
			//出库单Id查询item
			String prodoutId = request.getParameter("prodoutId");
			LogicProductionStorageoutDO prodout = logicProductionStorageOutService.findListById(prodoutId);
			if(prodout!=null){
				recpMoney.setZd009CustId(prodout.getZd012CustomerId());
				recpMoney.setZd009CustCode(prodout.getZd012CustomerCode());
				recpMoney.setZd009CustName(prodout.getZd012CustomerName());
			}
			List<LogicProductionStorageoutItemDO> prodoutItemList = logicProductionStorageOutService.findStorOutItemList(prodoutId);
			for(LogicProductionStorageoutItemDO prodoutItem : prodoutItemList){
				if(prodoutItem==null){
					continue;
				}
				BigDecimal price = prodoutItem.getZd009Price()==null?BigDecimal.ZERO:prodoutItem.getZd009Price();
				BigDecimal zdQuantity = prodoutItem.getZd007Quantity()==null?BigDecimal.ZERO:prodoutItem.getZd007Quantity();
				recpSum = recpSum.add(price.multiply(zdQuantity));
			}
			//赋值应收总额
			recpMoney.setZd004SumAmount(recpSum);
			//最后一次收款记录
			BigDecimal lastReceptMoney = logicReceptService.findLastReceptHasMoney(prodoutId);
			recpMoney.setZd005HasAmount(lastReceptMoney==null?BigDecimal.ZERO:lastReceptMoney);
		}catch(Exception e){
			e.printStackTrace();
		}
		return recpMoney;
	}
	
	/**
	 * 根据出库单ID查询销售出库单item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/prodSaleItemList")
	public void prodSaleItemList(HttpServletRequest request, HttpServletResponse response)throws Exception{
		String prodoutId = request.getParameter("prodoutId");
		if(StringUtils.isNotBlank(prodoutId)){
			//查询出库单的item集合
			List<LogicProductionStorageoutItemDO> prodoutItemList = logicProductionStorageOutService.findStorOutItemList(prodoutId);
			if(prodoutItemList==null){
				prodoutItemList = new ArrayList<LogicProductionStorageoutItemDO>();
			}
			List<LogicReceptDO> receptHisList = this.findReceptHisListByScs(prodoutId);
			List<LogicReceptItemDO> receptItemList = this.receptItemListComp(prodoutItemList,receptHisList);
			OutJsonGrid out = new OutJsonGrid(receptItemList);
			out.printJSon(response);
		}
	}
	
	/**
	 * 组装付款单的item集合列表
	 * @param prodoutItemList
	 * @param receptHisList
	 * @return
	 */
	private List<LogicReceptItemDO> receptItemListComp(List<LogicProductionStorageoutItemDO> prodoutItemList,List<LogicReceptDO> receptHisList){
		List<LogicReceptItemDO> receptItemList = new ArrayList<LogicReceptItemDO>();
		for(LogicProductionStorageoutItemDO prodoutItem : prodoutItemList){
			if(prodoutItem==null){
				continue;
			}
			LogicReceptItemDO receptItem = new LogicReceptItemDO();
			receptItem.setZd002MaterId(prodoutItem.getZd002MaterialsId());
			receptItem.setZd003MaterCode(prodoutItem.getZd002MaterialsCode());
			receptItem.setZd004MaterName(prodoutItem.getZd002MaterialsName());
			receptItem.setZd005Type("");
			receptItem.setZd006Spec(prodoutItem.getZd003MaterialsSpec());
			receptItem.setZd012Unit(prodoutItem.getZd006Unit());
			BigDecimal taxprice = prodoutItem.getZd009Price()==null?BigDecimal.ZERO:prodoutItem.getZd009Price();
			receptItem.setZd013Price(taxprice);
			//含税单价
			receptItem.setZd013TaxPrice(taxprice);
			//出库数量
			BigDecimal zdQuantity = prodoutItem.getZd007Quantity()==null?BigDecimal.ZERO:prodoutItem.getZd007Quantity();
			receptItem.setZd020Quantity(zdQuantity);
			//赋值应收总金额
			BigDecimal zdSumMoney = taxprice.multiply(zdQuantity);
			receptItem.setZd016Amount(zdSumMoney);
			if(receptHisList==null||receptHisList.isEmpty()||receptHisList.size()==0){
				//没有收款的历史记录
				receptItem.setZd019NoMoney(zdSumMoney);
				receptItem.setZd017HasMoney(BigDecimal.ZERO);
			}else{
				//存在历史的付款记录
				BigDecimal tempHsMoney = BigDecimal.ZERO;
				BigDecimal zdHsMoney = BigDecimal.ZERO;
				BigDecimal zdNoMoney = BigDecimal.ZERO;
				for(LogicReceptDO receptHis : receptHisList){
					if(receptHis==null || StringUtils.isBlank(receptHis.getId())){
						continue;
					}
					//查询物料的历史收款记录
					Map<String, Object> payItemMap = new HashMap<String, Object>();
					payItemMap.put("receptId", receptHis.getId());
					payItemMap.put("materId", prodoutItem.getZd002MaterialsId());
					List<LogicReceptItemDO> _receptItemList = logicReceptService.findItemListByMap(payItemMap); 
					if(_receptItemList==null || _receptItemList.isEmpty() || _receptItemList.size()==0){
						continue;
					}else{
						BigDecimal pzdThMoney = _receptItemList.get(0).getZd018TheMoney()==null?BigDecimal.ZERO:_receptItemList.get(0).getZd018TheMoney();
						tempHsMoney = tempHsMoney.add(pzdThMoney);
						//未付款
						zdNoMoney = zdSumMoney.subtract(tempHsMoney);
						//付款
						zdHsMoney = zdHsMoney.add(pzdThMoney);
					}
				}
				receptItem.setZd019NoMoney(zdNoMoney);
				receptItem.setZd017HasMoney(zdHsMoney);
			}
			receptItemList.add(receptItem);
		}
		return receptItemList;
	}
	
	/**
	 * 根据
	 * @param pcswId
	 * @return
	 * @throws SyBaseException
	 */
	@SuppressWarnings("unchecked")
	private List<LogicReceptDO> findReceptHisListByScs(String prodoutId)throws SyBaseException{
		SearchConditions payScs = new SearchConditions();
		payScs.setRemovedProperty(null);
		payScs.addCondition("zd002SaleId", prodoutId, SearchCondition.OP_EQUAL);
		SearchResult paySrs = logicReceptService.findListByExample(payScs);
		return paySrs.getResults();
	}
}
